import importlib
import logging
import queue
import threading

from host import host_dict
from tool import mns_time, mns_event, mns_communication as mns_com
import time
from ship import ship_adj_table


class Host(threading.Thread):
    def __init__(self, ship_name, message_queen_len: int = 512):
        super().__init__(name = ship_name)
        self.name = ship_name
        self.router = None
        self.queen_len = message_queen_len
        self.terminate_flag = False
        self.neighbors_list = []

    def run(self):
        """节点运行"""
        while not mns_time.Time.is_finish():
            # logging.info("节点线程" + self.name + "正在运行")
            time.sleep(0.000001)
            self.neighbors_list = ship_adj_table.Table.read(self.name)
            # 每个仿真间隙更新路由表
            self.update_router()
            while mns_com.MessageQueue.getById(self.name):
                self.router.receive_message(mns_com.MessageQueue.popById(self.name))
            self.router.send_message()
            while not self.router.send_array.empty():
                msg = self.router.send_array.get()
                logging.info(
                    "当前仿真时间为:" + str(
                        mns_time.Time.sim_time) + "," + self.name + "节点转发消息" + msg.toString())
                mns_com.MessageQueue.set(msg)
            # self.print_adj_list()

    def update_router(self):
        """更新路由表,每个仿真间隔才会运行"""
        if mns_time.Time.sim_time % mns_time.Time.step_size != 0:
            return
        else:
            # 等待更新路由表事件开始
            mns_event.MnsEvent.update_router_table_event.wait()
            # 获得当前邻居船只的所有host
            threading_list = host_dict.HostDict.get_by_names(self.neighbors_list)
            # 创建一个双层的dict
            d_dict = {}
            if threading_list:
                for thread in threading_list:
                    if isinstance(thread, Host):
                        d_dict[thread.name] = thread.router.table
                self.router.update_router_table(d_dict)

    def install_router(self, router_name: str, router_config: dict):
        module_name = "router.router"
        """安装路由"""
        try:
            # 动态导入模块
            module = importlib.import_module(module_name)
            # 获取类对象
            cls = getattr(module, router_name)
            # 实例化类
            instance = cls(self.name, router_config)
            self.router = instance
        except ImportError:
            logging.error(f"无法导入模块: {module_name}")
        except AttributeError:
            logging.error(f"模块 {module_name} 中没有名为 {router_name} 的类")

    def print_adj_list(self):
        if self.neighbors_list and len(self.neighbors_list) != 0:
            nei = self.neighbors_list[0]
            for i in range(1, len(self.neighbors_list)):
                nei += "," + self.neighbors_list[i]
            logging.info(
                "当前仿真时间" + str(mns_time.Time.sim_time) + "," + self.name + "邻居为" + "->" + nei)
        else:
            logging.info("当前仿真时间" + str(mns_time.Time.sim_time) + "," + self.name + "未发现邻居")

# if __name__ == '__main__':
#     host = Host()
#     host.install_router("Router")
